package gen.tools.email;

import gen.tools.Widgets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SendMail extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public SendMail() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/text");
		
		String res = "";
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		String subsysId = "fOrder";
		String envId = request.getParameter("envId");
		int tarDeliverySN = Integer.parseInt(request.getParameter( "tarDeliverySN" ) );
		int targetSystemId = Integer.parseInt(request.getParameter( "targetSystemId" ) );
		String localSystemName = request.getParameter("localSystemName");
		String msgBody = request.getParameter("msgBody");
		String subject = request.getParameter("subject");
		try {
			conn = wid.getConn();
			
			ArrayList<String[]> tos = wid.getRecipient(1, subsysId, envId,0);	//部署通知正本不需要這個參數，隨意寫入一整數
			ArrayList<String[]> ccs = wid.getRecipientCC(1, subsysId, envId, targetSystemId);
			ArrayList<String[]> bccs = new ArrayList<String[]>();
			//信件主旨
			subject = localSystemName+subject+tarDeliverySN;
			wid.sendMailMain(tos,ccs,bccs,subject, msgBody);
		} catch(Exception e) {
			res = wid.errLog(e);
		} finally {
			try {
				if ( rs !=null ) {rs.close();}
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		response.getWriter().write(res);
	}

}
